package com.lyx.rpc.serialization.fst;
import com.lyx.rpc.common.exception.SerializerException;
import com.lyx.rpc.serialization.api.Serialization;
import com.lyx.rpc.spi.annotation.SPIClass;
import org.nustaq.serialization.FSTConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author by lyx
 * Fst序列化与反序列化
 * 比JDK提供的序列化性能提升了10倍。
 * 序列化后的体积是JDK序列化的1/4~1/3。
 * 支持堆外Map，和堆外Map的持久化。
 * 支持序列化为JSON。
 */
@SPIClass
public class FstSerialization implements Serialization{
    private final Logger logger = LoggerFactory.getLogger(FstSerialization.class);
    @Override
    public <T> byte[] serialize(T obj) {
        logger.info("execute fst serialize...");
        if (obj == null){
            throw new SerializerException("serialize object is null");
        }
        FSTConfiguration conf = FSTConfiguration.getDefaultConfiguration();
        return conf.asByteArray(obj);
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> cls) {
        logger.info("execute fst deserialize...");
        if (data == null){
            throw new SerializerException("deserialize data is null");
        }
        FSTConfiguration conf = FSTConfiguration.getDefaultConfiguration();
        return (T) conf.asObject(data);
    }
}
